package com.shopping.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

public class FileUntils {
	private static final String TAG = "FileUntils";
	private static FileUntils fileUntils = null;

	private FileUntils() {

	}

	private String sdPath = Environment.getExternalStorageDirectory()
			+ "/watch/";// 获取sd卡目录

	/**
	 * 单例模式
	 */
	public static FileUntils getFileUntils() {
		if (fileUntils == null) {
			fileUntils = new FileUntils();
		}
		return fileUntils;
	}

	/**
	 * 在SD卡上创建文件
	 * 
	 * @param fileName
	 *            文件名
	 * @return 创建的文件
	 */
	public File CreatSDFile(String fileName) {
		File file = new File(fileName);
		try {
			file.createNewFile();
			Log.i(TAG, "文件创立成功");
		} catch (IOException e) {
			e.printStackTrace();
			Log.i(TAG, "文件创立失败");
			return null;
		}
		return file;
	}

	/**
	 * 在sd卡上创建文件夹
	 * 
	 * @param dirName
	 *            文件夹的名字
	 * @return 创建的文件夹
	 */
	public File createSDDir(String dirName) {
		File file = new File(dirName);
		file.mkdir();
		return file;
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param fileName
	 *            文件名
	 * @return true存在，false 不存在
	 */
	public boolean isFileExists(String fileName) {
		File file = new File(fileName);
		return file.exists();
	}

	/**
	 * 下载文件
	 * 
	 * @param fileURL
	 *            下载地址
	 * @param fileName
	 *            要下载的文件名
	 * @return 1：说明文件已经存在
	 */
	public int downLoadFile(String fileURL, String fileName) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		File file = null;
		if (isFileExists(sdPath + fileName)) {
			return 1;
		}
		try {
			URL url = new URL(fileURL);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			inputStream = http.getInputStream();
			createSDDir(sdPath);// 创建文件夹
			file = CreatSDFile(sdPath + fileName);// 创建文件
			outputStream = new FileOutputStream(file);
			byte buffer[] = new byte[16 * 1024];// 创建一个4k的字节组，用于存储数据
			int length = 0;
			int tol = 0;// 已经下载长度
			int tolalSize = http.getContentLength();// 获取数据总长度
			while ((length = inputStream.read(buffer)) != -1) {
				tol += length;
				outputStream.write(buffer, 0, length);
				Thread.sleep(100);
			}
			Log.i(TAG, "下载完成");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 图片下载
	 * 
	 * @param fileURL
	 *            图片地址
	 * @return
	 */
	public Drawable getImageDownload(String fileURL) {
		URL url;
		try {
			url = new URL(fileURL);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			InputStream inputStream = http.getInputStream();
			return Drawable.createFromStream(inputStream, null);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
